/*
 * @Descripttion : 时间日期选择器
 * @Versions     : 0.1
 * @Author       : foxui team
 * @Date         : 2022-03-06 11:38:30
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2023-02-28 16:59:17
 */

import { _nowDatetime } from './common/utils';
import { Pickertime } from './pickertime';
import { spinner } from './spinner';

function Pickerdatetime() {
    Pickertime.call(this);
    this.FILL_INPUT_HANDLE = '.foxui-datetime-picker .foxui-picker-bottom button.confirm';
    this.FILL_NOW_HANDLE = '.foxui-datetime-picker .foxui-picker-bottom button.now';
    this.FILL_DATE_INPUT_HANDLE = '.foxui-datetime-picker .foxui-picker-body__date .foxui-picker-content .available';
    this.FILL_DATE_INPUT = '.foxui-picker-top input.date';
    this.FILL_TIME_INPUT_HANDLE = '.foxui-datetime-picker .foxui-picker-top input.time';
    this.FILL_TIME_INPUT = '.foxui-picker-top input.time';
    this.JUMP_YEAR_HANDLE = '.foxui-datetime-picker .foxui-picker-body__month .foxui-picker-header .year, .foxui-datetime-picker .foxui-picker-body__date .foxui-picker-header .year';
    this.JUMP_MONTH_HANDLE = '.foxui-datetime-picker .foxui-picker-body__year .foxui-picker-content .available, .foxui-datetime-picker .foxui-picker-body__date .foxui-picker-header .month';
    this.JUMP_DATE_HANDLE = '.foxui-datetime-picker .foxui-picker-body__month .foxui-picker-content .available';
    this.HANDLE_CLASS = '.foxui-picker-handle';
    // 当前组件使用
    this.HANDLE = '.foxui-datetime-picker .foxui-picker-handle:not(.is-disabled)';
    // 内层
    this.INNER_MENU = '.foxui-picker__inner-menu';
    this.INNER_BODY = '.foxui-picker__inner-body';
    this.INNER_BOTTOM = '.foxui-picker__inner-bottom';
    this.INNER_CONFIRM = '.foxui-datetime-picker .foxui-picker__inner-menu button.inner-confirm';
    this.INNER_CANCEL = '.foxui-datetime-picker .foxui-picker__inner-menu button.inner-cancel';
}

Object.setPrototypeOf(Pickerdatetime.prototype, Pickertime.prototype);

Pickerdatetime.prototype._init = function () {
    this._bindToggle();
    this._bindJumpYear();
    this._bindJumpMonth();
    this._bindJumpDate();
    this._bindFillDateInput();
    this._bindFillTimeInput();
    this._bindFillInput();
    this._bindInnerToggle();
    this._clearInnerMenusByClickBlank();
    this._bindCloseInnerMenu();
};

Pickerdatetime.prototype._topHtml = function (handle) {
    let inputValue = $(handle).find('input').val(),
        datetimeArr = inputValue ? inputValue.split(' ') : [];

    return [
        '<div class="foxui-picker-top__inner foxui-clearfix">',
        `<input class="foxui-size-small date" readonly="readonly" placeholder="请选择日期" value="${datetimeArr[0] || ''}"/>`,
        `<input class="foxui-size-small time" readonly="readonly" placeholder="请选择时间" value="${datetimeArr[1] || ''}" />`,
        '</div>',
    ].join('');
};

Pickerdatetime.prototype._bodyHtml = function (handle) {
    let inputValue = $(handle).find('input').val(),
        datetimeArr = inputValue ? inputValue.split(' ') : [],
        dateArr = datetimeArr.length > 0 ? datetimeArr[0].split('-') : [];

    let bodyYearHtml = this._bodyYearHtml({ inputValue: datetimeArr[0], year: dateArr[0] }, true);
    let bodyMonthHtml = this._bodyMonthHtml({ inputValue: datetimeArr[0], year: dateArr[0], month: dateArr[1] }, true);
    let bodyDateHtml = this._bodyDateHtml({ inputValue: datetimeArr[0], year: dateArr[0], month: dateArr[1], date: dateArr[2] });

    return bodyYearHtml + bodyMonthHtml + bodyDateHtml;
};

Pickerdatetime.prototype._bottomHtml = function () {
    return '<button class="foxui-text-primary foxui-size-mini now">此刻</button><button class="foxui-plain foxui-size-mini confirm">确定</button>';
};

Pickerdatetime.prototype._bindFillDateInput = function () {
    let that = this;
    $(document).on('click', this.FILL_DATE_INPUT_HANDLE, function () {
        let $this = $(this),
            $container = $this.closest(that.CONTAINER),
            inputTime = $container.find(that.FILL_TIME_INPUT).val(),
            date = $this.attr('data-value');

        $container.find(that.FILL_DATE_INPUT).val(date);

        if (!inputTime) {
            let hasSeconds = $container.is('.has-seconds'),
                time = hasSeconds ? '00:00:00' : '00:00';
            $container.find(that.FILL_TIME_INPUT).val(time);
        }

        $this.closest('tbody').find('.available').removeClass('current');
        $this.addClass('current');
    });
};

Pickerdatetime.prototype._bindFillTimeInput = function () {
    let that = this;
    $(document).on('click', this.INNER_CONFIRM, function () {
        let $menu = $(this).closest(that.INNER_MENU),
            $input = $menu.siblings('.time'),
            $active = $menu.children(that.INNER_BODY).find(that.SPINNER_ITEM_ACTIVE),
            timeArr = [];

        $active.each(function () {
            timeArr.push($(this).text());
        });

        $input.val(timeArr.join(':'));
        $menu.slideUp('fast');
    });
};

Pickerdatetime.prototype._bindCloseInnerMenu = function () {
    let that = this;
    $(document).on('click', this.INNER_CANCEL, function () {
        $(this).closest(that.INNER_MENU).slideUp('fast');
    });
};

Pickerdatetime.prototype._bindFillInput = function () {
    let that = this;
    // 确定
    $(document).on('click', this.FILL_INPUT_HANDLE, function () {
        let { year, month, date, hours, minutes, seconds } = _nowDatetime(),
            $container = $(this).closest(that.CONTAINER),
            $input = $container.children(that.HANDLE_CLASS).find('input'),
            inputDate = $container.find(that.FILL_DATE_INPUT).val(),
            inputTime = $container.find(that.FILL_TIME_INPUT).val(),
            hasSeconds = $container.is('.has-seconds');

        month < 10 && (month = '0' + month);
        date < 10 && (date = '0' + date);
        hours < 10 && (hours = '0' + hours);
        minutes < 10 && (minutes = '0' + minutes);
        seconds < 10 && (seconds = '0' + seconds);

        let fillDate = inputDate || `${year}-${month}-${date}`;
        let fillTime = inputTime || (hasSeconds ? `${hours}:${minutes}:${seconds}` : `${hours}:${minutes}`);

        $input.val(fillDate + ' ' + fillTime);

        $container.find(that.MENU).slideUp('fast');
        $container.find(that.HANDLE_CLASS).removeClass('is-active');
    });

    // 此刻
    $(document).on('click', this.FILL_NOW_HANDLE, function () {
        let { year, month, date, hours, minutes, seconds } = _nowDatetime();

        month < 10 && (month = '0' + month);
        date < 10 && (date = '0' + date);
        hours < 10 && (hours = '0' + hours);
        minutes < 10 && (minutes = '0' + minutes);
        seconds < 10 && (seconds = '0' + seconds);

        let $container = $(this).closest(that.CONTAINER),
            $input = $container.children(that.HANDLE_CLASS).find('input'),
            hasSeconds = $container.is('.has-seconds'),
            dateTime = hasSeconds ? `${year}-${month}-${date} ${hours}:${minutes}:${seconds}` : `${year}-${month}-${date} ${hours}:${minutes}`;

        $input.val(dateTime);

        $container.find(that.MENU).slideUp('fast');
        $container.find(that.HANDLE_CLASS).removeClass('is-active');
    });
};

Pickerdatetime.prototype._bindInnerToggle = function () {
    let that = this;
    $(document).on('click', this.FILL_TIME_INPUT_HANDLE, function (event) {
        event.stopPropagation();

        let $this = $(this);
        let $container = $this.closest('.foxui-picker-top__inner');
        let $menu = $container.find(that.INNER_MENU);

        if ($menu.length < 1) {
            $container.append(`<div class="foxui-picker__inner-menu">${that._innerBodyHtml(this)}</div>`);
            $container.find(that.INNER_MENU).slideDown('fast');
        } else {
            if ($menu.css('display') === 'none') {
                $menu.empty().append(that._innerBodyHtml(this));
                $menu.slideDown('fast');
            } else {
                $menu.slideUp('fast');
                $this.blur();
            }
        }

        // 展开弹出面板 回调函数 -> 绑定滚动
        spinner._bindScrollForChrome();
        spinner._bindScrollForFirefox();

        // 展开弹出面板 回调函数 -> 设置滑板的位置
        let $slide = $container.find(that.SLIDE),
            $active = $container.find(that.SPINNER_ITEM_ACTIVE);

        $active.each(function (index) {
            let $this = $(this),
                eq = parseInt($this.text()),
                lineHeight = Math.round($this.height());

            $($slide[index]).scrollTop(lineHeight * eq);
        });
    });
};

Pickerdatetime.prototype._innerBodyHtml = function (input) {
    let { year, month, date, hours, minutes, seconds } = _nowDatetime();

    month < 10 && (month = '0' + month);
    date < 10 && (date = '0' + date);

    let $time = $(input),
        $date = $time.siblings('.date'),
        hasSeconds = $time.closest(this.CONTAINER).is('.has-seconds'),
        timeValue = $time.val(),
        dateValue = $date.val(),
        timeArr = timeValue ? timeValue.split(':') : [hours, minutes, seconds];

    dateValue || $date.val(`${year}-${month}-${date}`);

    return [
        '<div class="foxui-picker__inner-body">',
        '<div class="spinner-container">',
        `${this._spinnerHtml(24, timeArr[0])}${this._spinnerHtml(60, timeArr[1])}${hasSeconds ? this._spinnerHtml(60, timeArr[2]) : ''}`,
        '</div>',
        '</div>',
        '<div class="foxui-picker__inner-bottom">',
        '<button class="foxui-text-info foxui-size-mini inner-cancel">取消</button>',
        '<button class="foxui-text-primary foxui-size-mini inner-confirm">确定</button>',
        '</div>',
    ].join('');
};

Pickerdatetime.prototype._clearInnerMenusByClickBlank = function () {
    let that = this;
    $(document).on('click', this.MENU, function () {
        $(this).find(that.INNER_MENU).slideUp('fast');
    });

    $(document).on('click', this.INNER_BODY + ',' + this.INNER_BOTTOM, function (event) {
        event.stopPropagation();
    });
};

let pickerdatetime = new Pickerdatetime();

export { pickerdatetime };
